/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.helpdesk.webfilters;

import com.helpdesk.controllers.LoginController;
import com.helpdesk.controllers.util.Base64;
import com.helpdesk.controllers.util.Cookier;
import com.helpdesk.controllers.util.JsfUtil;
import com.helpdesk.entities.Accounts;
import com.helpdesk.entities.HelpDeskEnums;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author JK
 */
public class LoginFilter implements Filter {

    @EJB
    private com.helpdesk.beans.AccountsFacade ejbFacade;
    //vay kla xai duco roi

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = (HttpSession) req.getSession(true);
        Accounts acc = (Accounts) session.getAttribute(LoginController.currentUserKey);
        if (acc == null) {
            Cookie[] cookies = req.getCookies();
            if (Cookier.exist("_ua")) {
                try {
                    String value = new String(Base64.decode(Cookier.getValue("_ua")));
                    String[] us = value.split("\\|");
                    acc = ValidateUser(us[0], us[1]);
                } catch (IOException ex) {
                    JsfUtil.addErrorMessage(ex, null);
                    Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);

                }
            }

        }
        if (acc != null) {
            try {
                session.setAttribute("currentUser", acc);
                resp.sendRedirect(acc.getHomePageUrl());

            } catch (Exception e) {
                JsfUtil.addErrorMessage(e, null);
                Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, e);
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    /**
     * Validate user by username and password
     *
     * @param username
     * @param password
     * @return Account
     */
    public final Accounts ValidateUser(String username, String password) {
        Accounts acc = ejbFacade.findByUsername(username);
        if ((acc != null && acc.getPassword().equals(password))) {
            return acc;
        }
        return null;
    }

    @Override
    public void destroy() {
    }
}
